{% extends 'index.html' %}
{% block page-title %}主机管理| 批量文件{% endblock %}
{% block header-resources %}
    <link href="/static/plugins/fileinput/css/fileinput.min.css" media="all" rel="stylesheet" type="text/css"/>
{% endblock %}
{% block page-content %}{% csrf_token %}
    <div class="row">
        <div class="col-lg-3">
            <div class="panel panel-info">
                <div class="panel-heading">
                    <h3 class="panel-title">主机列表</h3>
                </div>
                <div class="panel-body">
                    <div class="list-group bord-no">
                        {% for host_group in request.user.host_groups.select_related %}
                            <a onclick="hostlistdisplay(this)" class="list-group-item" href="#">
                                <input class="magic-checkbox" type="checkbox" onclick="selecrgroup(this)">
                                {{ host_group.name }}
                                <span class="badge badge-primary">{{ host_group.bind_hosts.count }}</span>
                            </a>
                            <ul class="hide">
                                {% for bind_host in host_group.bind_hosts.all %}
                                    <li class="list-group-item">
                                        <input class="magic-checkbox" select_host="ture" value="{{ bind_host.id }}"
                                               type="checkbox">{{ bind_host }}
                                    </li>
                                {% endfor %}
                            </ul>
                        {% endfor %}
                        <a onclick="hostlistdisplay(this)" class="list-group-item" href="#">
                            <input class="magic-checkbox" type="checkbox" onclick="selecrgroup(this)">
                            未分组
                            <span class="badge badge-primary">{{ request.user.bind_hosts.count }}</span>
                        </a>
                        <ul class="hide">
                            {% for bind_host in request.user.bind_hosts.all %}
                                <li class="list-group-item">
                                    <input class="magic-checkbox" select_host="ture" value="{{ bind_host.id }}"
                                           type="checkbox">{{ bind_host }}
                                </li>
                            {% endfor %}
                        </ul>
                    </div>
                </div>
            </div>
        </div>
        <div class="col-lg-9">
            {% csrf_token %}
            <input id="file-input-id" type="file" multiple class="file-loading" data-preview-file-type="text">
            <div  style="margin-top: 20px">
                <input id="remote_path" type="text" placeholder="要上传到远程机器上的绝对路径" class="form-control">
                <button id="host_task_btn" type="button" onclick="posttask(this)" class="btn btn-lg btn-default btn-hover-primary pull-right"
                            style="margin-top: 10px;height: 40px">执行命令
                </button>
            </div>
        </div>
    </div>
    <div class="row" style="margin-top: 20px">
        <div class="panel panel-info">
            <div class="panel-heading">
                <h3 class=" panel-title">执行结果</h3>
            </div>
            <div class="panel-body">
                <ul id="task_result_container"></ul>
            </div>
        </div>
    </div>


    <script src="/static/plugins/fileinput/js/plugins/piexif.min.js" type="text/javascript"></script>

    <script src="/static/plugins/fileinput/js/plugins/sortable.min.js" type="text/javascript"></script>

    <script src="/static/plugins/fileinput/js/plugins/purify.min.js" type="text/javascript"></script>

    <script src="/static/plugins/fileinput/js/fileinput.min.js"></script>

    <script src="/static/plugins/fileinput/js/locales/zh.js"></script>
    <script>
        $(document).ready(function () {
            $("#file-input-id").fileinput({
                uploadUrl: "{% url 'file_upload' %}",
                uploadAsync: true,
                language: "zh",
                maxFilesize: 2000,
                maxFileCount: 5,
            });
        });

        function hostlistdisplay(ele) {
            $(ele).next().toggleClass("hide");
        }

        function selecrgroup(ele) {
            $(ele).parent().next().find("input").prop("checked", $(ele).prop("checked"))
        }


        function GetTaskResult(task_id) {
            $.getJSON("{% url 'task_result' %}", {'task_id': task_id}, function (callback) {
                console.log(callback);
                var all_task_done = true;
                $.each(callback, function (index, ele) {
                    var li_ele = $("li[bind_host_id='" + ele['id'] + "']");
                    li_ele.next().text(ele['result']);
                    $(li_ele.children()[0]).text(ele.status);
                    if (ele.status == 2){
                        all_task_done = false; //有任务未完成
                    }
                });
                if (all_task_done){
                        clearInterval(ResultRefreshObj);
                        $("#host_task_btn").removeClass("disabled")
                }
            });//end getJson
        }
        function PushTaskIdIntoRequestHeader(task_id) {
            $.ajaxSetup({
                beforeSend: function (xhr,settings) {
                    xhr.setRequestHeader("task_id",task_id)
                }
            })
        }
        
        function posttask(ele) {
            var selected_host_ids = [];
            $("input[select_host]:checked").each(function () {
                selected_host_ids.push($(this).val())
            });
            if (selected_host_ids.length == 0) {
                alert("请选择主机");
                return false
            }

            var remote_path = $("#remote_path").val().trim();

            if (remote_path.length == 0) {
                alert("请输入需要远程服务器路径");
                return false
            }
            var file_list = [];
            $(".file-footer-caption").each(function () {
                console.log($(this).attr("title"));
                file_list.push($(this).attr("title"));
            });

            if (file_list.length ==0 ){
                alert("请选择需要上传的文件");
                return false
            }
            var task_arguments = {
                'selected_host_ids': selected_host_ids,
                'task_type': 1,//cmd
                'remote_path': remote_path,

            };
            console.log(task_arguments);
            //在次任务执行完之前，不允许再执行
            $(ele).addClass("disabled");
            //提交任务之前，先清空任务面板
            $("#task_result_container").empty();

            $.post("{% url 'multitask' %}", {
                'task_data': JSON.stringify(task_arguments),
                'csrfmiddlewaretoken': $("input[name='csrfmiddlewaretoken']").val()
            }, function (callback) {

                var callback = JSON.parse(callback);

{#                PushTaskIdIntoRequestHeader(callback['task_id']);#}
                $("#file-input-id").fileinput('upload');
                console.log(callback);

                $.each(callback.selected_hosts, function (index, ele) {
                    var li_ele = "<li bind_host_id='" + ele['id'] + "'>Host:" + ele.bind_host__host__hostname + "(" + ele.bind_host__host__ip_addr + ")--------------<span></span></li><pre></pre>";
                    $("#task_result_container").append(li_ele);


                });

                //后端定时拿结果
                ResultRefreshObj = setInterval(function () {
                    GetTaskResult(callback.task_id);
                }, 2000)

            });
        }

    </script>
{% endblock %}